/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package otros;

import java.awt.Color;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.CodeSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Properties;
import javax.swing.DefaultCellEditor;
import javax.swing.JFormattedTextField;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.api.ColorSchemeAssociationKind;
import org.jvnet.substance.api.ComponentState;
import tablasSql.Articulos;
import tablasSql.Compras;
import tablasSql.FacturasAlbaranes;
import tablasSql.Stock;

/**
 *
 * @author FERRETERIA
 */
public class Util {
    
     public final static String FTPV = "tpv";
     public final static String FCOMPRAS = "compras";
     public final static String FFACTURAS = "facturas";
     public final static String FFACCOMPRAS = "FacCompras";
     
    
     public final static String LOG4_FICH = "log4j.properties";
    
     private final static Logger log = Logger.getLogger(Util.class);
     private static Properties p = null;
    
     public static Color getBackground(int row, int filaSel, JTable jtable, boolean selected, boolean fuera){
         Color color = jtable.getBackground();
         if (row % 2 == 0)
                color = jtable.getBackground();
         else
             if (SubstanceLookAndFeel.getCurrentSkin(jtable) != null)
                color = (SubstanceLookAndFeel.getCurrentSkin(jtable).
                          getColorScheme(jtable, ComponentState.DEFAULT).getLightColor());
         if (selected) { 
            if (filaSel == row) {
                    color =  UIManager.getColor("Table.selectionBackground");                   
            }
            else {
                 if (SubstanceLookAndFeel.getCurrentSkin(jtable) != null)
                    color =  SubstanceLookAndFeel.getCurrentSkin(jtable).
                              getColorScheme(jtable,ColorSchemeAssociationKind.HIGHLIGHT, 
                                   ComponentState.SELECTED).getUltraLightColor();
                 }

          } else
             if ((row == filaSel) && (!fuera)) {
                 if (SubstanceLookAndFeel.getCurrentSkin(jtable) != null)
                     color = SubstanceLookAndFeel.getCurrentSkin(jtable).
                                 getColorScheme(jtable,ColorSchemeAssociationKind.HIGHLIGHT, 
                                      ComponentState.SELECTED).getWatermarkLightColor();
             }         
         return color;
    }
    
    public static Color getForeground(int row, int filaSel, JTable jtable, boolean selected, boolean fuera) {
        Color color = jtable.getForeground();
        if (selected) 
            color = UIManager.getColor("Table.selectionForeground"); 
        else
            if ((row == filaSel) && (!fuera))
                color = UIManager.getColor("Table.selectionForeground"); 
        return color;
    }
    
    public static void restaurarStock(int id, int tipo, boolean restar) {
        Util.setConfiguracionLog(Util.LOG4_FICH);
        ResultSet res = FacturasAlbaranes.getListArticulos(id, tipo);
        try {
            while (res.next()) {
                if(res.getString("idarticulo")!= null) {
                    float cantidad = res.getFloat("cantidad");
                    cantidad = (restar)? -cantidad : cantidad;
                    Stock.menosStock(res.getString("idarticulo"), cantidad);
                }
            }
        } catch (SQLException ex) { 
            log.warn(ex);
        }
    }
    
    public static void restaurarStock(int id, boolean restar) {
        Util.setConfiguracionLog(Util.LOG4_FICH);
        ResultSet res = Compras.getListArticulos(id);
        try {
            while (res.next()) {
                if(res.getString("idarticulo")!= null) {
                    float cantidad = res.getFloat("cantidad");
                    cantidad = (restar)? -cantidad : cantidad;  
                    Stock.menosStock(res.getString("idarticulo"), cantidad);
                }
            }
        } catch (SQLException ex) { 
            log.warn(ex);
        }
    }
    
    public static String getRuta() {
         try {
             CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource();
             File jarFile = new File(codeSource.getLocation().toURI().getPath());
             File jarDir = jarFile.getParentFile();
             return jarDir.getAbsolutePath();
         } catch (URISyntaxException ex) {
             log.warn("Error en direccion:" + ex.getMessage());
         }
         return "";
    }
    
    
    public static Properties obtenerArchivoPropiedades(String arc) {
        Properties prop = null;
        try {
            CodeSource codeSource = Util.class.getProtectionDomain().getCodeSource();
            File jarFile = new File(codeSource.getLocation().toURI().getPath());
            File jarDir = jarFile.getParentFile();
    
            if(jarDir != null && jarDir.isDirectory()) {
                File propFile = new File(jarDir, arc);
                prop = new Properties();
                prop.load(new BufferedReader(new FileReader(propFile.getAbsoluteFile())));
            }
        } catch (URISyntaxException ex) {
              log.warn("error en direccion: " + ex.getMessage());
        } catch (FileNotFoundException ex) {
            log.warn("No se encuentra el archivo: " + ex.getMessage());
            //throw new FileNotFoundException("No se econtró el archivo de propiedades...");
        } catch (IOException ex) {
             log.warn("error en entrada salida: " + ex.getMessage());
        }
        return prop;
    }
    
    
    public static void setConfiguracionLog(String nameFich) {
        if (p == null)
            p = obtenerArchivoPropiedades("conf/"+nameFich);
        if (p.isEmpty())
            PropertyConfigurator.configure(nameFich);
        else
            PropertyConfigurator.configure(p);
    }
        
    public static String getFormatPrecio(Object valor, int numDec) {
        DecimalFormat df;
        switch (numDec) {
            case 4:
                df = new DecimalFormat("#0.0000");
                break;
            case 3:
                df = new DecimalFormat("#0.000");
                break;
            default:
                df = new DecimalFormat("#0.00");
                break;    
        }
        try {
            return String.valueOf(df.format(valor)).replace(".", ",") + "€";
        } catch (Exception e) {
            return String.valueOf(df.format(0)).replace(".", ",") + "€";
        }
    }
    
    public static double redondeo5(double num, int d) {
        String valor = "" + num;
        int pComa = valor.indexOf(".");
        int numD = valor.length()-1-pComa;
        
        if (d <= numD) {
            if (d < numD) num = Math.round(num*Math.pow(10,d))/Math.pow(10,d);
            int ultD = (int)(num*Math.pow(10,d)) % 10; 

            if (ultD < 3) 
                num -= (ultD*Math.pow(10,-d)); 
            else if ((ultD >= 3) && (ultD < 8))
                num += ((5-ultD)*Math.pow(10,-d));
            else
                num += ((10-ultD)*Math.pow(10,-d));
        }    
        
        return Math.round(num*Math.pow(10,d))/Math.pow(10,d);
    }
    
    public static float redondeo(double valor, int numDec) {
        if (Double.isNaN(valor)) 
            return 0;
        DecimalFormat df;
        switch (numDec) {
            case 4:
                df = new DecimalFormat("#0.0000");
                break;
            case 3:
                df = new DecimalFormat("#0.000");
                break;
            default:
                df = new DecimalFormat("#0.00");
                break;    
        }
        
        String aux = df.format(valor).replace(",",".");
        return Float.parseFloat(aux);
    }
    
    public static Color getColorTicket (String estado) {
        switch (estado.toLowerCase()) {
            case "factura":     
                    return Color.yellow;
            case "albaran":      
                    return Color.CYAN;
            case "presupuesto":
                    return Color.green;
            case "abono":
                    return Color.red;
            case "fiado":
                    return Color.MAGENTA;
            default:
                return Color.white;
        }            
    }
    
}
